package com.rop.system.util;

import cn.hutool.core.collection.CollUtil;
import com.rop.model.system.SysMenu;
import com.rop.model.vo.MetaVo;
import com.rop.model.vo.RouterVo;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Title: RouterHelper
 * @Author Rop
 * @Date 2023/4/27 9:59
 * @description: 根据菜单信息构建路由的工具类
 */

public class RouterHelper {

    /**
     * 根据菜单构建路由
     * @param menus 菜单信息
     * @return 路由
     */
    public static List<RouterVo> buildRouters(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(false);
            router.setAlwaysShow(false);
            router.setPath(getRouterPath(menu));
            router.setComponent(menu.getComponent());
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
            List<SysMenu> children = menu.getChildren();

            // 如果当前是菜单，需要按钮对应的路由加载出来，
            if (Objects.equals(menu.getType(), 1)) {
                List<SysMenu> hiddenMenuList = children.stream()
                        .filter(t -> StringUtils.isNotBlank(t.getComponent()))
                        .collect(Collectors.toList());

                for (SysMenu sysMenu : hiddenMenuList) {
                    RouterVo hiddenRouter = new RouterVo();
                    hiddenRouter.setHidden(true);
                    hiddenRouter.setAlwaysShow(false);
                    hiddenRouter.setPath(getRouterPath(sysMenu));
                    hiddenRouter.setComponent(sysMenu.getComponent());
                    hiddenRouter.setMeta(new MetaVo(sysMenu.getName(), sysMenu.getIcon()));
                    routers.add(hiddenRouter);
                }

            } else {

                if (CollUtil.isNotEmpty(children)) {
                    if (children.size() > 0) {
                        router.setAlwaysShow(true);
                    }
                    router.setChildren(buildRouters(children));
                }

            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由地址
     *
     * @param sysMenu 菜单信息
     * @return 路由地址
     */
    public static String getRouterPath(SysMenu sysMenu) {
        String routerPath = "/" + sysMenu.getPath();

        if (!Objects.equals(sysMenu.getParentId().intValue(), 0)) {
            routerPath = sysMenu.getPath();
        }

        return routerPath;
    }
}
